
import { isLoginFn } from '@/utils/common'
import { Toast } from 'vant';
//  定义路由文件
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter);


// 路由懒加载:
// 定义: 不一次性加载所有的组件, 而是当路由访问到哪一个组件,才去加载对应的组件
// 优点: 解决首页加载慢的问题, 防止首页白屏
// 语法: () => import('@/views/Home.vue');

// 定义路由映射表
const routes = [
    {
        path: '/',
        redirect: '/home'
    },
    {
        path: '/home',
        name: 'home',
        component: () => import('@/views/Home.vue'),
        meta: {
            isshowtabbar: true  // 是否显示tabbar
        }
    },
    {
        path: '/cart',
        name: 'cart',
        component: () => import('@/views/Cart.vue'),
        meta: {
            isshowtabbar: false
        }
    },
    {
        path: '/user',
        name: 'user',
        component: () => import('@/views/User.vue'),
        meta: {
            isshowtabbar: true
        }
    },
    {
        path: '/login',
        name: 'login',
        component: () => import('@/views/Login.vue'),
        meta: {
            isshowtabbar: false
        }
    },
    {
        path: '/detail/:id',
        name: 'detail',
        component: () => import('@/views/Detail.vue'),
        meta: {
            isshowtabbar: false
        }
    },
    {
        path: '/regist',
        name: 'regist',
        component: () => import('@/views/Regist.vue'),
        meta: {
            isshowtabbar: false
        },
        children: [
            {
                path: 'step1',
                name: 'step1',
                component: () => import('@/views/Step1.vue')
            },
            {
                path: 'step2',
                name: 'step2',
                component: () => import('@/views/Step2.vue')
            },
            {
                path: 'step3',
                name: 'step3',
                component: () => import('@/views/Step3.vue')
            }
        ]
    },
    {
        // 404路由
        path: '*',
        component: () => import('@/views/Notfind.vue'),
        meta: {
            isshowtabbar: false
        }
    }

]

// 创建路由对象
const router = new VueRouter({
    mode: 'history',
    routes // (缩写) 相当于 routes: routes
})


// 定义一个路由全局前置守卫
router.beforeEach((to, from, next) => {
    // 判断当访问购物车路由的时候, 才进行守卫, 否则其他都正常放行
    if (to.path == '/cart') {
        if (isLoginFn()) {
            //表示存在token,说明登录过了
            next()
        } else {
            Toast({
                type: 'fail',
                message: '请先登录',
                duration: 1500,
                onClose: () => {
                    router.push('/login')
                }

            })
        }
    } else {
        next()
    }

})



export default router



